package com.example.demo.controller;

import com.example.demo.ai.DeepSeekService;
import com.example.demo.ai.model.ResumeAnalysis;
import com.example.demo.entity.Resume;
import com.example.demo.entity.User;
import com.example.demo.service.FileParserService;
import com.example.demo.service.ResumeService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/resume")
public class ResumeController {

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private DeepSeekService deepSeekService;
    
    @Autowired
    private FileParserService fileParserService;
    
    @Autowired
    private UserService userService;

    @GetMapping("/analysis")
    public String showResumeAnalysisPage(Model model) {
        model.addAttribute("resume", new Resume());
        return "resume/analysis";
    }

    @PostMapping("/analyze")
    public String analyzeResume(@RequestParam("file") MultipartFile file,
                               @RequestParam("resumeText") String resumeText,
                               @RequestParam(value = "jobTitle", required = false) String jobTitle,
                               @RequestParam(value = "jobDescription", required = false) String jobDescription,
                               Authentication authentication, Model model) {
        try {
            // 初始化简历内容变量
            String finalResumeText = resumeText;
            String filename = null;
            String filePath = null;

            // 处理文件上传
            if (file != null && !file.isEmpty()) {
                System.out.println("收到文件上传请求，文件名: " + file.getOriginalFilename());
                
                // 检查文件类型是否支持
                if (!fileParserService.isSupportedFileType(file)) {
                    model.addAttribute("errorMessage", "不支持的文件类型，请上传PDF或DOCX格式");
                    return "resume/analysis";
                }
                
                // 检查上传目录是否存在
                File uploadDir = new File("C:/uploads/");
                if (!uploadDir.exists()) {
                    boolean created = uploadDir.mkdirs();
                    System.out.println("上传目录创建结果: " + created);
                }
                
                filename = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
                filePath = "C:/uploads/" + filename;
                
                try {
                    // 保存文件
                    file.transferTo(new File(filePath));
                    
                    // 如果用户没有填写简历文本，但上传了文件，则从文件中提取内容
                    if (resumeText == null || resumeText.trim().isEmpty()) {
                        // 使用FileParserService解析文件内容
                        finalResumeText = fileParserService.parseFile(new File(filePath));
                        // 如果解析结果为空，设置默认提示文本
                        if (finalResumeText == null || finalResumeText.trim().isEmpty()) {
                            finalResumeText = "简历文件: " + file.getOriginalFilename() + " (文件已上传，内容为空或解析失败)";
                        }
                    }
                    
                    // 创建简历对象并设置文件信息
                    Resume resume = new Resume();
                    if (authentication != null) {
                        String username = authentication.getName();
                        User user = userService.findByUsername(username);
                        if (user != null) {
                            resume.setUserId(user.getId());
                        }
                    }
                    resume.setResumeText(finalResumeText);
                    resume.setFileName(filename);
                    resume.setFilePath(filePath);
                    
                    // 保存简历信息
                    resumeService.save(resume);
                } catch (IOException e) {
                    System.out.println("文件上传失败: " + e.getMessage());
                    model.addAttribute("errorMessage", "文件上传失败: " + e.getMessage());
                    return "resume/analysis";
                }
            } else if (resumeText == null || resumeText.trim().isEmpty()) {
                model.addAttribute("errorMessage", "请上传简历文件或粘贴简历内容");
                return "resume/analysis";
            }

            // 分析简历内容
            ResumeAnalysis resumeAnalysis;
            if (jobTitle != null && !jobTitle.trim().isEmpty()) {
                // 带岗位信息的简历分析
                resumeAnalysis = deepSeekService.analyzeResume(finalResumeText, jobTitle, jobDescription);
            } else {
                // 基础简历分析
                resumeAnalysis = deepSeekService.analyzeResume(finalResumeText);
            }

            model.addAttribute("resumeAnalysis", resumeAnalysis);
            model.addAttribute("resumeContent", finalResumeText);
            return "resume/result";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("errorMessage", "简历分析失败：" + e.getMessage());
            return "resume/analysis";
        }
    }
}